'use strict';

angular.module('CBO').controller('DeviceMonitorInfosController', ['$scope', 'BaseService', 'BaseModule', 'BaseEnum', 'CBOEnum', 'BaseConst', 'BaseFunction', 'Authentication',
    function($scope, BaseService, BaseModule, BaseEnum, CBOEnum, BaseConst, BaseFunction, Authentication) {
        $scope.ExecuteResultEnum = CBOEnum.ExecuteResult;
        $scope.TerminalTypeEnum = BaseFunction.getEnum('CBOEnum.TerminalType');
        $scope.TerminalType = 1;

        BaseModule.initModule($scope, 'Department');
        BaseModule.initModule($scope, 'WorkLocation');
        BaseModule.initModule($scope, 'StationTerminal');
        BaseModule.initModule($scope, 'StationWork');
        BaseModule.initModule($scope, 'DeviceMonitor');

        $scope.Module.DeviceMonitor.LoadMode = BaseEnum.LoadMode.CacheAndPaging;
        $scope.Module.DeviceMonitor.OrderBy = {RequestTime: -1};
        $scope.Module.DeviceMonitor.PageSize = 15;

        $scope.Department = null;
        $scope.FocusedRecord = null;

        function getChildDepartmentIds(departmentIds, returnFun){
            $scope.Module.Department.find(
                {
                    ParentDepartment: {$in: departmentIds}
                },
                null, null, function(records){
                    var departments = [];
                    if(records.length > 0){
                        for(var i=0; i<records.length; i++){
                            departments.push(records[i]._id);
                        }
                    }
                    returnFun(departments);
                }
            );
        };

        function getAllChildDepartmentIds(departmentIds, returnFun){
            var returnAllIds = departmentIds;
            var resultFun = function(departIds){
                if(departIds.length > 0){
                    returnAllIds = returnAllIds.concat(departIds);
                    getChildDepartmentIds(departIds, resultFun);
                }
                else{
                    returnFun(returnAllIds);
                }
            }
            
            getChildDepartmentIds(departmentIds, resultFun);
        };

        $scope.onTerminalTypeChange = function(){
            if($scope.Department){
                $scope.onDepartmentChange();
            }
        };

        $scope.onDepartmentChange = function(){
            $scope.FocusedRecord = null;
            if($scope.Department){
                getAllChildDepartmentIds([$scope.Department._id], function(departmentIds){
                    //通过部门找工位
                    $scope.Module.WorkLocation.find(
                        {
                            Department: {$in: departmentIds}
                        },
                        null, null, function(wRecords){
                            var wRecordIds = [];
                            if(wRecords.length > 0){
                                for(var i=0; i<wRecords.length; i++){
                                    wRecordIds.push(wRecords[i]._id);
                                }
                                //通过工位找终端
                                $scope.Module.StationTerminal.find(
                                    {
                                        WorkLocation: {$in: wRecordIds},
                                        'Terminal.Type': $scope.TerminalType
                                    },
                                    null, [{path: 'Terminal'}, {path: 'WorkLocation'}],
                                    function(stRecords){
                                        //通过工位找作业
                                        var wlIds = [];
                                        stRecords.forEach(function (stRecord) {
                                            if(stRecord.Terminal.LastRequestDate){
                                                stRecord.Terminal._LastRequestDate = BaseFunction.dateTimeToString(new Date(stRecord.Terminal.LastRequestDate));
                                            }
                                            wlIds.push(stRecord.WorkLocation._id);
                                        });

                                        $scope.Module.StationWork.find(
                                            {
                                                WorkLocation: {$in : wlIds}
                                            },
                                            null, {path: 'Work', select: 'Name'},
                                            function(swRecords){
                                                swRecords.forEach(function (swRecord) {
                                                    for(var i=0; i<stRecords.length; i++){
                                                        if(stRecords[i].WorkLocation._id == swRecord.WorkLocation){
                                                            stRecords[i].Terminal._Work = swRecord.Work;
                                                            break;
                                                        }
                                                    }
                                                });
                                                findDeviceMonitorInfos(stRecords);
                                            }
                                        );
                                    }
                                );
                            }
                            else{
                                findDeviceMonitorInfos([]);
                            }                            
                        }
                    );
                });
            }
            else{
                $scope.DisplayRecords = [];
                // displayTerminals();
            }
        };

        $scope.terminalClick = function(record){
            $scope.FocusedRecord = record;
        };

        $scope.DisplayRecords = [];

        $scope.CardReaderImg = "CardReader.png";
        $scope.ConnectColor = "#FF7A8D";
        $scope.AnalyzeColor = "#FF940A";
        $scope.NormalColor = "#3CC6B6";

        var findDeviceMonitorInfos = function(stRecords){
            if(stRecords.length > 0){
                var connectRecords = [];
                var analyzeRecords = [];
                var returnRecords = [];
                var uniqueIDs = [];

                BaseService.getSysDateTime().then(function(sysDate){
                    for(var i=0; i<stRecords.length; i++){
                        if(stRecords[i].Terminal.IsEffective === true){
                            //设置显示图片
                            if(stRecords[i].Terminal.Type == CBOEnum.TerminalType.WiFi.Value){
                                stRecords[i].Terminal._Img = $scope.CardReaderImg;
                            }
                            
                            var date = new Date(sysDate);
                            date.setSeconds(date.getSeconds() - 120);
                            var date2 = stRecords[i].Terminal.LastRequestDate ? new Date(stRecords[i].Terminal.LastRequestDate) : BaseConst.DateTime.Min;
                            if(date.getTime() >= date2.getTime()){          //连接超时
                                stRecords[i].Terminal._Color = $scope.ConnectColor;
                                connectRecords = connectRecords.concat(stRecords.splice(i, 1));
                                i--;
                            }
                            else{   //正常或者解析异常
                                uniqueIDs.push(stRecords[i].Terminal.UniqueID);
                                stRecords[i].Terminal._Color = $scope.NormalColor;
                            }
                        }
                        else{
                            stRecords.splice(i, 1);
                            i--;
                        }
                    }

                    if(uniqueIDs.length > 0){
                        //查解析异常
                        //条件还未确认，只取第一个
                        var condition = {TerminalUniqueID: {$in: uniqueIDs}, IsProcess: {$ne: true}, ExecuteResult: CBOEnum.ExecuteResult.AnalyzeException.Value};
                        findDeviceMonitor(condition).then(function(dmRecords){
                            for(var i=0; i<dmRecords.length; i++){
                                for(var j=0; j<stRecords.length; j++){
                                    if(dmRecords[i].TerminalUniqueID == stRecords[j].Terminal.UniqueID){
                                        stRecords[j].Terminal._Color = $scope.AnalyzeColor;
                                        stRecords[j].Terminal.ExceptionInfo = dmRecords[i].ExceptionInfo;
                                        analyzeRecords = analyzeRecords.concat(stRecords.splice(j, 1));
                                        break;
                                    }
                                }
                            }

                            $scope.DisplayRecords = connectRecords.concat(analyzeRecords).concat(stRecords);
                            // displayTerminals();
                            $scope.$digest();
                        }).catch(function(err){
                            BaseFunction.errFun(err);
                        });
                    }
                    else{
                        $scope.DisplayRecords = connectRecords;
                        // displayTerminals();
                    }
                });
            }
            else{
                $scope.DisplayRecords = [];
                // displayTerminals();
            }
        };
        var findDeviceMonitor = function(condition){
            var promise = new Promise(function(resolve, reject) {
                $scope.Module.DeviceMonitor.aggregate([
                        {$match: condition},
                        {$group : {_id : '$' + 'TerminalUniqueID', RequestTime : {$max: '$' + 'RequestTime'}}},
                        {$sort: {value: 1}}
                    ]).then(function(datas){
                        var dmRecords = [];
                        datas.forEach(function(data){
                            dmRecords.push({
                                TerminalUniqueID: data._id,
                                RequestTime: data.RequestTime
                            });
                        });
                        if(dmRecords.length > 0){
                            $scope.Module.DeviceMonitor.find({$or: dmRecords}, null, null, function(dmRecords){
                                resolve(dmRecords);
                            }, function(err){
                                reject(err);
                            });
                        }
                        else{
                            resolve(dmRecords);
                        }
                });
            });
            return promise;
        };

        $scope.btnLookException = function(record){
            $scope.terminalClick(record);
            $scope.Module.DeviceMonitor.Condition = {
                ExecuteResult: {$ne: 0},
                TerminalUniqueID: $scope.FocusedRecord.Terminal.UniqueID
            };

            $scope.Module.DeviceMonitor.load(
                null, 
                null,
                function(dmRecords){
                    $('#' + document.getElementById('lookException').children[1].getAttribute('id')).modal('show');
                }
            );
        };
    }
]);